package com.ruicar.afs.cloud.manage.common.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.basic.api.fegin.info.BasicInfoFeign;
import com.ruicar.afs.cloud.basic.api.reappear.DowdTemRule;
import com.ruicar.afs.cloud.basic.api.reappear.DowdTemVo;
import com.ruicar.afs.cloud.bizcommon.dto.rules.tree.RuleTreeDto;
import com.ruicar.afs.cloud.bizcommon.enums.rules.RuleStatus;
import com.ruicar.afs.cloud.bizcommon.print.entity.ComPrintFormManage;
import com.ruicar.afs.cloud.bizcommon.print.enums.ServiceClientTypeEnum;
import com.ruicar.afs.cloud.bizcommon.print.service.ComPrintFormManageService;
import com.ruicar.afs.cloud.bizcommon.rules.entity.AfsRuleInfo;
import com.ruicar.afs.cloud.bizcommon.rules.entity.AfsRuleItem;
import com.ruicar.afs.cloud.bizcommon.rules.service.AfsRuleInfoService;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.*;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.image.config.FileProperties;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.manage.common.entity.ManageReprintRecord;
import com.ruicar.afs.cloud.manage.common.mapper.ManageReprintRecordMapper;
import com.ruicar.afs.cloud.manage.common.service.ManageReprintRecordService;
import com.ruicar.afs.cloud.manage.common.util.CreatCaseNoUtil;
import com.ruicar.afs.cloud.manage.contractreissur.vo.ContractReissurManageVo;
import com.ruicar.afs.cloud.manage.workflow.entity.WorkTaskCreatedInfo;
import com.ruicar.afs.cloud.manage.workflow.enums.NormalSubmitEnum;
import com.ruicar.afs.cloud.manage.workflow.enums.WorkflowTypeEnum;
import com.ruicar.afs.cloud.manage.workflow.processor.ContractWorkFlowSaveApproveInfoProcessor;
import com.ruicar.afs.cloud.manage.workflow.service.WorkTaskCreatedInfoService;
import com.ruicar.afs.cloud.manage.workflow.service.WorkflowSubmitService;
import com.ruicar.afs.cloud.manage.workflow.vo.TaskSubmitVO;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.StartFlowRequest;
import com.ruicar.afs.cloud.workflow.gwt.service.WorkflowService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: Lee
 * @date 2020-05-30 04:45:15
 * @description
 */
@Slf4j
@Service
@AllArgsConstructor
public class ManageReprintRecordServiceImpl extends ServiceImpl<ManageReprintRecordMapper, ManageReprintRecord> implements ManageReprintRecordService {

    private final FileProperties fileProperties;
    private final WorkflowSubmitService workflowSubmitService;
    private final ContractWorkFlowSaveApproveInfoProcessor saveApproveInfoProcessor;
    private final WorkflowService workflowService;
    private WorkTaskCreatedInfoService workTaskCreatedInfoService;
    private final ManageReprintRecordMapper manageReprintRecordMapper;
    private final ComPrintFormManageService comPrintFormManageService;
    private final BasicInfoFeign basicInfoFeign;
    private final ComAttachmentFileService comAttachmentFileService;
    private final AfsRuleInfoService afsRuleInfoService;

    /**
     * 保存合同重出
     *
     * @param vo
     */
    @Override
    public ContractReissurManageVo saveContractReissue(ContractReissurManageVo vo) {
        if (vo.getId() == null) {
            if (EmptyUtils.isEmpty(vo.getSelecteds())) {
                throw new AfsBaseException(CommonConstants.FAIL, "请选择最少一个合同!");
            }
            SaveContract(vo);
            ContractReissurManageVo vo1 = new ContractReissurManageVo();
            BeanUtils.copyProperties(vo, vo1);
            return vo1;
        } else {
            ManageReprintRecord byId = getById(vo.getId());
            if (!byId.getProcessStatus().equals(ProcessStatusEnum.draft) && !byId.getProcessStatus().equals(ProcessStatusEnum.toBeRepaired)) {
                throw new AfsBaseException(CommonConstants.FAIL, "此合同编号已流程中！");
            }
            if (EmptyUtils.isEmpty(vo.getSelecteds())) {
                throw new AfsBaseException(CommonConstants.FAIL, "请选择最少一个合同!");
            }
            List<ComPrintFormManage> versionList = vo.getSelecteds();
            JSONArray jsonArray = new JSONArray();
            for (ComPrintFormManage comPrintFormManage : versionList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("printNode", comPrintFormManage.getPrintNode());
                jsonObject.put("printFormName", comPrintFormManage.getPrintFormName());
                jsonObject.put("versionId", comPrintFormManage.getVersionId());
                jsonArray.add(jsonObject);
            }
            vo.setContractList(jsonArray.toJSONString());
            updateById(byId);
            ContractReissurManageVo vo1 = new ContractReissurManageVo();
            BeanUtils.copyProperties(byId, vo1);
            return vo1;
        }
    }


    /**
     * 提交合同重出并且提交审批流程
     *
     * @param vo
     */
    @Override
    public void submitContractReissue(ContractReissurManageVo vo) {
        if (vo.getId() == null) {
            //生成案件编号
            SaveContract(vo);
        }
//        List<ComPrintFormManage> selecteds = vo.getSelecteds();
//        String contractNo = vo.getContractNo();
//        IResponse<DowdTemRule> dowdTemRuleIResponse = basicInfoFeign.contractQueryRule(contractNo);
//        for (ComPrintFormManage selected : selecteds) {
//            ComPrintFormManage getComPrintFormManage = comPrintFormManageService.getOne(Wrappers.<ComPrintFormManage>query().lambda()
//                    .eq(ComPrintFormManage::getPrintFormName, selected.getPrintFormName())
//                    .eq(ComPrintFormManage::getVersionId, selected.getVersionId())
//            );
//            AfsRuleInfo afsRuleInfo = afsRuleInfoService.getOne(Wrappers.<AfsRuleInfo>query().lambda()
//                    .eq(AfsRuleInfo::getRuleNo, getComPrintFormManage.getId())
//                    .eq(AfsRuleInfo::getStatus, RuleStatus.ACTIVE)
//            );
//            if (EmptyUtils.isNotEmpty(afsRuleInfo)){
//                List<RuleTreeDto> ruleTreeDtos = afsRuleInfoService.loadRuleTree(afsRuleInfo.getId());
//                for (RuleTreeDto ruleTreeDto : ruleTreeDtos) {
//                    List<RuleTreeDto> rows = ruleTreeDto.getRows();
//                    for (RuleTreeDto row : rows) {
//                        dowdTemRuleIResponse.getData().getBusinessType();
//                        if (row.getExpress().getLeft())
//                    }
//
//                }
//            }
//
//        }
        //提交审核,发起流程
        if (vo.getProcessStatus().equals(ProcessStatusEnum.draft)) {
            if (EmptyUtils.isEmpty(vo.getSelecteds())) {
                throw new AfsBaseException(CommonConstants.FAIL, "请选择最少一个合同!");
            }
            vo.setProcessStatus(ProcessStatusEnum.underReview);
            vo.setId(vo.getId());
            updateById(vo);
            StartFlowRequest startFlowRequest = new StartFlowRequest();
            startFlowRequest.setFlowName((StringUtils.isEmpty(vo.getContractNo()) ? "" : (vo.getContractNo()) + "-") + AfsEnumUtil.desc(WorkflowTypeEnum.CONTRACT_REISSUR));
            startFlowRequest.setBizDataId(String.valueOf(vo.getId()));
            startFlowRequest.setAfsFlowKey(AfsEnumUtil.key(WorkflowTypeEnum.CONTRACT_REISSUR));
            String jsonString = JSONObject.toJSONString(vo);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            //保存审批记录
            //保存代办任务
            saveApproveInfoProcessor.saveApproveInfo(vo, ContractBusinessEnum.reprintContract, CaseStatusEnum.UNDER_REVIEW, BusinessUrlEnum.CONTRACT_REISSUR);
            TaskSubmitVO taskSubmitVO = new TaskSubmitVO();
            taskSubmitVO.setBizData(jsonObject);
            workflowSubmitService.saveRecord(taskSubmitVO, AfsEnumUtil.desc(NormalSubmitEnum.SUGGEST_CHECK_FINAL));
            workflowService.startWorkFlow(startFlowRequest, jsonObject);
        } else {
            if (EmptyUtils.isEmpty(vo.getSelecteds())) {
                throw new AfsBaseException(CommonConstants.FAIL, "请选择最少一个合同!");
            }
            vo.setProcessStatus(ProcessStatusEnum.repairedUnderReview);
            vo.setId(vo.getId());
            updateById(vo);
            StartFlowRequest startFlowRequest = new StartFlowRequest();
            startFlowRequest.setAfsFlowKey(AfsEnumUtil.key(WorkflowTypeEnum.CONTRACT_REISSUR));
            startFlowRequest.setBizDataId(String.valueOf(vo.getId()));
            startFlowRequest.setFlowName(AfsEnumUtil.desc(WorkflowTypeEnum.CONTRACT_REISSUR));
            String jsonString = JSONObject.toJSONString(vo);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            //保存审批记录
            saveApproveInfoProcessor.saveApproveInfo(vo, ContractBusinessEnum.reprintContract, CaseStatusEnum.UNDER_REVIEW, BusinessUrlEnum.CONTRACT_REISSUR);
            TaskSubmitVO taskSubmitVO = new TaskSubmitVO();
            String json = JSONObject.toJSONString(vo);
            JSONObject custInfoJson = JSONObject.parseObject(json);
            taskSubmitVO.setBizData(custInfoJson);
            taskSubmitVO.setReasonType(vo.getReasonType());
            taskSubmitVO.setApprovalOpinion(vo.getApprovalOpinion() != null ? vo.getApprovalOpinion() : null);
            taskSubmitVO.setApprovalOperating("suggestCheckF");
//            taskSubmitVO.setBizData(jsonObject);
//            taskSubmitVO.setApprovalOpinion(vo.getApprovalOpinion());
//            taskSubmitVO.setApprovalOperating(vo.getApprovalOperating());
//            taskSubmitVO.setReasonType(vo.getReasonType());
            workflowSubmitService.submit(taskSubmitVO);
            vo.setProcessStatus(ProcessStatusEnum.repairedUnderReview);
            updateById(vo);
        }
    }

    /**
     * 合同重出流程审批
     *
     * @param vo
     */
    @Override
    public boolean saveProposalApplicationInfo(ContractReissurManageVo vo) {
        Boolean flag = false;

        CaseStatusEnum caseStatusEnum = null;
        ProcessStatusEnum processStatusEnum = null;
        if (AfsEnumUtil.key(NormalSubmitEnum.SUGGEST_CHECK_FINAL).equals(vo.getApprovalOperating())) {
            WorkTaskCreatedInfo workTaskCreatedInfo = workTaskCreatedInfoService.getOne(Wrappers.<WorkTaskCreatedInfo>query().lambda()
                    .eq(WorkTaskCreatedInfo::getBizDataId, vo.getId().toString()).orderByDesc(WorkTaskCreatedInfo::getCreateTime), false
            );
            if (ProcessStatusEnum.approved.name().equals(workTaskCreatedInfo.getTaskMemo())) {
                if (EmptyUtils.isEmpty(vo.getSelecteds())) {
                    throw new AfsBaseException(CommonConstants.FAIL, "请选择最少一个合同!");
                }
                vo.setEndDate(DateUtil.date());
                caseStatusEnum = CaseStatusEnum.APPROVED;
                processStatusEnum = ProcessStatusEnum.approved;
                printContract(vo);
            } else if (ProcessStatusEnum.end.name().equals(workTaskCreatedInfo.getTaskMemo())) {
                vo.setEndDate(DateUtil.date());
                caseStatusEnum = CaseStatusEnum.APPROVED;
                processStatusEnum = ProcessStatusEnum.approved;
            } else {
                caseStatusEnum = CaseStatusEnum.UNDER_REVIEW;
                processStatusEnum = ProcessStatusEnum.underReview;
            }
            vo.setProcessStatus(processStatusEnum);
            saveApproveInfoProcessor.saveApproveInfo(vo, ContractBusinessEnum.reprintContract, caseStatusEnum, BusinessUrlEnum.CONTRACT_REISSUR);
        } else if (AfsEnumUtil.key(NormalSubmitEnum.SUGGEST_REJECT_FINAL).equals(vo.getApprovalOperating())) {
            vo.setEndDate(DateUtil.date());
            vo.setProcessStatus(ProcessStatusEnum.refuse);
            saveApproveInfoProcessor.saveApproveInfo(vo, ContractBusinessEnum.reprintContract, CaseStatusEnum.REFUSE, BusinessUrlEnum.CONTRACT_REISSUR);
        } else if (AfsEnumUtil.key(NormalSubmitEnum.SEND_BACK).equals(vo.getApprovalOperating())) {
            WorkTaskCreatedInfo workTaskCreatedInfo = workTaskCreatedInfoService.getOne(Wrappers.<WorkTaskCreatedInfo>query().lambda()
                            .eq(WorkTaskCreatedInfo::getBizDataId, vo.getId())
                            .orderByDesc(WorkTaskCreatedInfo::getCreateTime)
                    , false
            );
            vo.setEndDate(DateUtil.date());
//            vo.setProcessStatus(ProcessStatusEnum.toBeRepaired);
            //初审时返回待补件状态，否则返回上一轮审核
            if ((workTaskCreatedInfo.getTaskMemo()).equals("approved")) {
                vo.setProcessStatus(ProcessStatusEnum.toBeRepaired);
            } else {
                vo.setProcessStatus(ProcessStatusEnum.underReview);
            }
            saveApproveInfoProcessor.saveApproveInfo(vo, ContractBusinessEnum.reprintContract, CaseStatusEnum.NOT_SUBMIT, BusinessUrlEnum.CONTRACT_REISSUR);
        }
        updateById(vo);
        String jsonString = JSONObject.toJSONString(vo);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        TaskSubmitVO taskSubmitVO = new TaskSubmitVO();
        taskSubmitVO.setBizData(jsonObject);
        taskSubmitVO.setApprovalOperating(vo.getApprovalOperating());
        taskSubmitVO.setApprovalOpinion(vo.getApprovalOpinion());
        taskSubmitVO.setReasonType(vo.getReasonType());
        workflowSubmitService.submit(taskSubmitVO);
        return flag;
    }

    @Override
    public List<ContractReissurManageVo> queryContract(ContractReissurManageVo vo) {
        List<ContractReissurManageVo> objects = new ArrayList<>();
        if (EmptyUtils.isNotEmpty(vo.getCaseNo())) {
            List<ManageReprintRecord> manageReprintRecordList = list(Wrappers.<ManageReprintRecord>query().lambda()
                    .eq(ManageReprintRecord::getContractNo, vo.getContractNo())
                    .eq(ManageReprintRecord::getProcessStatus, ProcessStatusEnum.approved)
                    .orderByDesc(ManageReprintRecord::getCreateTime));
            ManageReprintRecord manageReprintRecord = null;
            if (EmptyUtils.isNotEmpty(manageReprintRecordList) && manageReprintRecordList.size() != 0) {
                manageReprintRecord = manageReprintRecordList.get(0);
            }
            String caseNo = manageReprintRecord.getCaseNo();
            ContractReissurManageVo contractReissurManageVoRe = new ContractReissurManageVo();
            contractReissurManageVoRe.setBusiNo(caseNo);
            contractReissurManageVoRe.setPrintNode("printLoanApply");
            List<ContractReissurManageVo> list = manageReprintRecordMapper.queryContract(contractReissurManageVoRe);
            if (list.size() == 0) {
                throw new AfsBaseException(CommonConstants.FAIL, "目前没有合同!");
            }
            ContractReissurManageVo contractReissurManageVo = null;
            for (ContractReissurManageVo reissurManageVo : list) {
                contractReissurManageVo = new ContractReissurManageVo();
                contractReissurManageVo.setPrintFormName(reissurManageVo.getPrintFormName());
                List<ComPrintFormManage> getVersionIdList = comPrintFormManageService.list(
                        Wrappers.<ComPrintFormManage>query().lambda()
                                .eq(ComPrintFormManage::getPrintFormName, reissurManageVo.getPrintFormName())
                                .eq(ComPrintFormManage::getPrintNode, vo.getPrintNode())
                );
                List<ComPrintFormManage> versionList = new ArrayList<>();
                for (ComPrintFormManage comPrintFormManage : getVersionIdList) {
                    versionList.add(comPrintFormManage);
                }
                contractReissurManageVo.setVersionList(versionList);
                objects.add(contractReissurManageVo);
            }
        }
        return objects;

    }

    @Override
    public List<ContractReissurManageVo> queryContractByScene(ContractReissurManageVo vo) {
        List<ContractReissurManageVo> list = manageReprintRecordMapper.queryContract(vo);
//        IResponse<DowdTemRule> dowdTemRuleIResponse = basicInfoFeign.contractQueryRule(vo.getContractNo());
//        if (list.size() > 0 && EmptyUtils.isNotEmpty(list)) {
//            for (int i = 0; i < list.size(); i++) {
//                if (list.get(i).getPrintFormName().equals("购车确认声明")) {
//
//                    if (dowdTemRuleIResponse.getData().getInvoice() == null || dowdTemRuleIResponse.getData().getInvoice().equals("yes")) {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    }
//                }
//                if (list.get(i).getPrintFormName().equals("车辆挂靠协议")) {
//                    List affiliatedWays = dowdTemRuleIResponse.getData().getAffiliatedWays();
//                    if (affiliatedWays != null) {
//                        for (Object affiliatedWay : affiliatedWays) {
//                            if (affiliatedWay.equals(AffiliatedWayEnum.COMPANY_AFFILIATED.name())) {
//                                continue;
//                            } else if (affiliatedWay.equals(AffiliatedWayEnum.NETWORK_CAR_AFFILIATED.name())) {
//                                continue;
//                            } else {
//                                list.remove(list.get(i));
//                                i--;
//                                continue;
//                            }
//                        }
//                        continue;
//                    } else {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    }
//
//                }
//                if (list.get(i).getPrintFormName().equals("汽车贷款合同")) {
//                    if (dowdTemRuleIResponse.getData().getBusinessType() == null) {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    }
//                }
//                if (list.get(i).getPrintFormName().equals("贷款知情确认函（二手车）")) {
//                    if (dowdTemRuleIResponse.getData().getBusinessType() == null || dowdTemRuleIResponse.getData().getBusinessType().equals(BusinessTypeEnum.newCar)) {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    } else if (dowdTemRuleIResponse.getData().getAddLoans() == null || dowdTemRuleIResponse.getData().getAddLoans().equals("no")) {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    }
//                }
//                if (list.get(i).getPrintFormName().equals("结构化产品补充协议")) {
//                    if (dowdTemRuleIResponse.getData().getRepayMode() != null && dowdTemRuleIResponse.getData().getRepayMode().equals("6")) {
//
//                    } else {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    }
//                }
//                if (list.get(i).getPrintFormName().equals("汽车抵押合同")) {
//                    if (dowdTemRuleIResponse.getData().getBusinessType() == null) {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    }
//                    List affiliatedWays = dowdTemRuleIResponse.getData().getAffiliatedWays();
//                    if (affiliatedWays != null) {
//                        for (Object affiliatedWay : affiliatedWays) {
//                            if (affiliatedWay.equals("NO")) {
//                                list.remove(list.get(i));
//                                i--;
//                                continue;
//                            }
//                        }
//                        continue;
//                    } else {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    }
//                }
//                if (list.get(i).getPrintFormName().equals("汽车抵押贷款合同（承德）")) {
//                    if (dowdTemRuleIResponse.getData().getLicenseCity() != null && dowdTemRuleIResponse.getData().getLicenseCity().equals("130800")) {
//
//                    } else {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    }
//                }
//                if (list.get(i).getPrintFormName().equals("二手车买卖及委托支付确认协议")) {
//                    if (dowdTemRuleIResponse.getData().getBusinessType() != null && dowdTemRuleIResponse.getData().getBusinessType().equals(BusinessTypeEnum.oldCar)) {
//
//                    } else {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    }
//                }
//                if (list.get(i).getPrintFormName().equals("汽车抵押贷款合同（佛山）")) {
//                    if (dowdTemRuleIResponse.getData().getLicenseCity() != null && dowdTemRuleIResponse.getData().getLicenseCity().equals("440600")) {
//
//                    } else {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    }
//                }
////            if (getComPrintFormManage.getPrintFormName().equals("汽车抵押贷款合同（无共借和担保）")){
////                List affiliatedWays = dowdTemRuleIResponse.getData().getAffiliatedWays();
////                for (Object affiliatedWay : affiliatedWays) {
////
////                }
////            }
////            if (getComPrintFormManage.getPrintFormName().equals("汽车抵押贷款合同（鲜章）")){
////                List affiliatedWays = dowdTemRuleIResponse.getData().getAffiliatedWays();
////                for (Object affiliatedWay : affiliatedWays) {
////
////                }
////            }
//                if (list.get(i).getPrintFormName().equals("贷款知情确认函(新车)")) {
//                    if (dowdTemRuleIResponse.getData().getBusinessType() != null && dowdTemRuleIResponse.getData().getBusinessType().equals(BusinessTypeEnum.newCar)) {
//
//                    } else if (dowdTemRuleIResponse.getData().getAddLoans() != null && dowdTemRuleIResponse.getData().getAddLoans().equals("yes")) {
//
//                    } else {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    }
//                }
//                if (list.get(i).getPrintFormName().equals("贷款知情确认函LCV")) {
//                    if (dowdTemRuleIResponse.getData().getBusinessType() != null && dowdTemRuleIResponse.getData().getBusinessType().equals(BusinessTypeEnum.newCar)) {
//
//                    } else if (dowdTemRuleIResponse.getData().getBusinessType() != null && dowdTemRuleIResponse.getData().getBusinessType().equals(BusinessTypeEnum.oldCar)) {
//
//                    } else {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    }
//                }
//                if (list.get(i).getPrintFormName().equals("汽车抵押贷款合同")) {
//                    if (dowdTemRuleIResponse.getData().getLicenseCity() != null && dowdTemRuleIResponse.getData().getLicenseCity().equals("530100")) {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    } else if (dowdTemRuleIResponse.getData().getLicenseCity() != null && dowdTemRuleIResponse.getData().getLicenseCity().equals("440600")) {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    } else if (dowdTemRuleIResponse.getData().getLicenseCity() != null && dowdTemRuleIResponse.getData().getLicenseCity().equals("130800")) {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    }
//                }
//                if (list.get(i).getPrintFormName().equals("汽车抵押贷款合同（昆明）")) {
//                    if (dowdTemRuleIResponse.getData().getLicenseCity() != null && dowdTemRuleIResponse.getData().getLicenseCity().equals("530100")) {
//
//                    } else {
//                        list.remove(list.get(i));
//                        i--;
//                        continue;
//                    }
//                }
//            }
//        }
        List<ContractReissurManageVo> arrayList = new ArrayList<>();
        if (list.size() == 0) {
            throw new AfsBaseException(CommonConstants.FAIL, "没有可打印的合同模板！");
        }
        ContractReissurManageVo contractReissurManageVo = null;
        for (ContractReissurManageVo reissurManageVo : list) {
            contractReissurManageVo = new ContractReissurManageVo();
            contractReissurManageVo.setPrintFormName(reissurManageVo.getPrintFormName());
            List<ComPrintFormManage> getVersionIdList = comPrintFormManageService.list(
                    Wrappers.<ComPrintFormManage>query().lambda()
                            .eq(ComPrintFormManage::getPrintFormName, reissurManageVo.getPrintFormName())
                            .eq(ComPrintFormManage::getPrintNode, vo.getPrintNode())
            );
            List<ComPrintFormManage> versionList = new ArrayList<>();
            for (ComPrintFormManage comPrintFormManage : getVersionIdList) {
                versionList.add(comPrintFormManage);
            }
            contractReissurManageVo.setVersionList(versionList);
            arrayList.add(contractReissurManageVo);
        }
        return arrayList;
    }


    @Override
    public List<ContractReissurManageVo> queryNewContract(ContractReissurManageVo vo) {
        ContractReissurManageVo contractReissurManageVoOther = new ContractReissurManageVo();
        contractReissurManageVoOther.setBusiNo(vo.getContractNo());
        List<ContractReissurManageVo> comAttachementFileList = manageReprintRecordMapper.queryFile(contractReissurManageVoOther);
        List<ContractReissurManageVo> contractReissurManageVoList = new ArrayList<>();
        if (EmptyUtils.isNotEmpty(comAttachementFileList) && comAttachementFileList.size() > 0) {
            for (ContractReissurManageVo comAttachementFile : comAttachementFileList) {
                String attachmentName = comAttachementFile.getAttachmentName();
                ContractReissurManageVo contractReissurManageVo = new ContractReissurManageVo();
                contractReissurManageVo.setContractNo(vo.getContractNo());
                contractReissurManageVo.setAttachmentName(attachmentName);
                contractReissurManageVo.setVersionId(comAttachementFile.getHistoryVersion());
                contractReissurManageVo.setPrintNode("printLoanApply");
                contractReissurManageVo.setPrintFormName(attachmentName);
                contractReissurManageVo.setAttachmentCode(comAttachementFile.getAttachmentCode());
                List<ComPrintFormManage> contractReissurManageVoListNow = new ArrayList<>();
                ComPrintFormManage comPrintFormManage = comPrintFormManageService.getById(contractReissurManageVo.getAttachmentCode());
                contractReissurManageVoListNow.add(comPrintFormManage);
                contractReissurManageVo.setVersionList(contractReissurManageVoListNow);
                contractReissurManageVoList.add(contractReissurManageVo);
            }
        }

        return contractReissurManageVoList;
    }

    @Override
    public List<ContractReissurManageVo> addNewContract(ContractReissurManageVo vo) {
        return null;
    }


    @Override
    public boolean downContractList(HttpServletResponse response, ContractReissurManageVo vo) {

        ManageReprintRecord manageReprintRecord = getOne(Wrappers.<ManageReprintRecord>query().lambda()
                .eq(ManageReprintRecord::getCaseNo, vo.getCaseNo())
        );
        String contractList = manageReprintRecord.getContractList();
        List<ComPrintFormManage> comPrintFormManages = JSONObject.parseArray(contractList, ComPrintFormManage.class);
        List<ComAttachmentFile> comAttachementFileList = new ArrayList<>();
        for (ComPrintFormManage comPrintFormManage : comPrintFormManages) {
            ComPrintFormManage comPrintFormManageServiceOne = comPrintFormManageService.getOne(Wrappers.<ComPrintFormManage>query().lambda()
                    .eq(ComPrintFormManage::getPrintFormName, comPrintFormManage.getPrintFormName())
                    .eq(ComPrintFormManage::getVersionId, comPrintFormManage.getVersionId())
                    .eq(ComPrintFormManage::getPrintNode, comPrintFormManage.getPrintNode())
            );
            ComAttachmentFile comAttachementFile = comAttachmentFileService.getOne(Wrappers.<ComAttachmentFile>query().lambda()
                    .eq(ComAttachmentFile::getBusiNo, manageReprintRecord.getContractNo())
                    .eq(ComAttachmentFile::getAttachmentCode, comPrintFormManageServiceOne.getId())
            );
            comAttachementFileList.add(comAttachementFile);
        }

        Date endDate = manageReprintRecord.getEndDate();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = df.format(endDate.getTime() + 15 * 24 * 60 * 60 * 1000);
        Date parse = null;

        try {
            parse = df.parse(startTime);
        } catch (Exception e) {
            log.error("", e);
            throw new AfsBaseException("时间换算失败");
        }
        // 1-临时目录
        String destPath = fileProperties.getTempDir() + File.separator + manageReprintRecord.getCaseNo() + File.separator + DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomNumber();
        // 2-远程下载
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", comAttachmentFileService.getAuthorization());
        for (ComAttachmentFile attachmentFile : comAttachementFileList) {
            if (parse.before(attachmentFile.getCreateTime())) {
                throw new AfsBaseException(CommonConstants.FAIL, "合同重出已失效,请重新申请业务！");
            }
            byte[] fileByte = comAttachmentFileService.downloadAttachmentFile(attachmentFile);
            if (fileByte.length > 0) {
                FileUtil.writeBytes(fileByte, destPath + File.separator + attachmentFile.getFileName());
            }

        }
        BufferedInputStream bufferedInputStream = null;
        try {
            String zipFileName = UUID.randomUUID().toString() + ".zip";
            File zipFile = ZipUtil.zip(destPath);
            response.reset(); // 重点突出
            if (FileUtil.exist(destPath)) {
                File file = FileUtil.file(zipFile);
                bufferedInputStream = FileUtil.getInputStream(file);
                response.setContentType("application/json");
                response.setHeader("Content-Disposition", "attachment;filename=" + HttpUtil.encodeUtf8(zipFileName));
                IoUtil.copy(bufferedInputStream, response.getOutputStream(), 1024);
                response.getOutputStream().flush();
                IoUtil.close(bufferedInputStream);
                //删除打包文件
                FileUtil.del(destPath);
                return true;
            }
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (Exception e) {
            IoUtil.close(bufferedInputStream);
            FileUtil.del(destPath);
            log.error("文件下载失败:" + e.getMessage());
        } finally {
            IoUtil.close(bufferedInputStream);
        }


        return true;
    }


    public void printContract(ContractReissurManageVo vo) {
        //审批通过之后添加模板信息到合同重出表中
        List<ComPrintFormManage> versionList = vo.getSelecteds();
        List<ComAttachmentFile> comAttachementFiles = new ArrayList<>();
        for (ComPrintFormManage comPrintFormManage : versionList) {
            if (comPrintFormManage.getVersionId() == null || comPrintFormManage.getVersionId() == "") {
                throw new AfsBaseException(CommonConstants.FAIL, "请选择合同模板！");
            }
            ComPrintFormManage getComPrintFormManage = comPrintFormManageService.getOne(Wrappers.<ComPrintFormManage>query().lambda()
                    .eq(ComPrintFormManage::getPrintFormName, comPrintFormManage.getPrintFormName())
                    .eq(ComPrintFormManage::getVersionId, comPrintFormManage.getVersionId())
            );

            IResponse<DowdTemVo> dowdTemVoIResponse = basicInfoFeign.contractQuery(vo.getContractNo());
            Assert.isTrue(CommonConstants.SUCCESS.equals(dowdTemVoIResponse.getCode()), "获取合同信息有误！");
            DowdTemVo dowdTemVo = dowdTemVoIResponse.getData();
            JSONObject jsonTemp = (JSONObject) JSONObject.toJSON(dowdTemVo);
            ComAttachmentFile print = comPrintFormManageService.print(jsonTemp, String.valueOf(getComPrintFormManage.getId()), vo.getCaseNo(), AfsEnumUtil.key(ServiceClientTypeEnum.PC));
            print.setHistoryVersion(comPrintFormManage.getVersionId());
            comAttachementFiles.add(print);
        }

        JSONArray jsonArray = new JSONArray();
        for (ComPrintFormManage comPrintFormManage : versionList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("printNode", comPrintFormManage.getPrintNode());
            jsonObject.put("printFormName", comPrintFormManage.getPrintFormName());
            jsonObject.put("versionId", comPrintFormManage.getVersionId());
            jsonArray.add(jsonObject);
        }
        vo.setContractList(jsonArray.toJSONString());
        updateById(vo);
    }

    @Override
    public IPage getReprintRecordList(Page page, ContractReissurManageVo vo) {

        return this.baseMapper.getReprintRecordList(page, vo);
    }

    @Override
    public IPage getPartReprintRecordList(Page page, ContractReissurManageVo vo) {

        return this.baseMapper.getPartReprintRecordList(page, vo);
    }

    private void SaveContract(ContractReissurManageVo vo) {
        //生成案件编号
        vo.setCaseNo(CreatCaseNoUtil.GeneratorCaseNo(ContractBusinessEnum.reprintContract));
        vo.setProcessStatus(ProcessStatusEnum.draft);
        vo.setApplyDate(DateUtil.date());
        vo.setDataSource(DataSourceEnum.icos);
        vo.setApplyBy(SecurityUtils.getUser().getUserRealName());
        List<ComPrintFormManage> versionList = vo.getSelecteds();
        JSONArray jsonArray = new JSONArray();
        for (ComPrintFormManage comPrintFormManage : versionList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("printNode", comPrintFormManage.getPrintNode());
            jsonObject.put("printFormName", comPrintFormManage.getPrintFormName());
            jsonObject.put("versionId", comPrintFormManage.getVersionId());
            jsonArray.add(jsonObject);
        }
        vo.setContractList(jsonArray.toJSONString());
        save(vo);
    }


}
